#!d:\anaconda3\envs\office_automation\python.exe
# coding=utf-8
r"""
author: git config IVEN_CN && git config 13377529851@QQ.com
Date: 2024-01-18 11:29:11 +0800
LastEditTime: 2024-08-20 14:23:10 +0800
FilePath: \office_automation\cutter\cut.py
details: 将提供的800*1200尺寸的图片居中裁剪成800*800和750*1000

Copyright (c) 2024 by IVEN, All Rights Reserved. 
"""
import os
import PIL.Image
import cv2
import re
import numpy as np


def cut_img_(path1200: str, path1000: str = "./", path800: str = "./"):
    """将提供的800*1200尺寸的图片居中裁剪成800*800和750*1000

    :param path1200: 800*1200图片的路径
    :param path1000: 750*1000图片的路径
    :param path800: 800*800图片的路径
    """

    # img = cv2.imread(path1200)
    # 用PIL读取图片
    img = PIL.Image.open(path1200)
    img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    if img.shape != (1200, 800, 3):
        raise ValueError("图片尺寸不正确")

    # img1 = img[200+15:1000+15, :]       # 800*800   
    img1 = img[200:1000, :]       # 800*800
    img2 = img[100:1100, 25:25+750]     # 750*1000
    match = re.search(r'\((\d+)\)', path1200)
    if match is not None:
        num = match.group(1)
    else:
        raise TypeError('没有匹配到括号内的数字')

    name800 = '800(' + num + ').jpg'
    name1000 = '1000(' + num + ').jpg'

    path1000 = os.path.join(path1000, name1000)
    path800 = os.path.join(path800, name800)

    # 用pil存储图片
    img2 = PIL.Image.fromarray(cv2.cvtColor(img2, cv2.COLOR_BGR2RGB))
    img2.save(path1000, quality=99, optimize=True)
    img1 = PIL.Image.fromarray(cv2.cvtColor(img1, cv2.COLOR_BGR2RGB))
    img1.save(path800, quality=99, optimize=True)


def cut_img(path, filename):
    """
    裁剪图片

    :param path: 图片所在文件夹的路径
    :param filename: 图片的文件名"""
    _path = os.path.join(path, filename)
    cut_img_(_path, path, path)


def cut_cut(*filename, path):
    """
    裁剪多张图片 

    :param filename: 图片的文件名，例如1200 (1).jpg
    :param path: 图片文件夹的路径"""
    for i in filename:
        cut_img(path,i)


def resize1200(*filename, path):
    img_paths = [os.path.join(path, i) for i in filename]
    for img_path in img_paths:
        # img = cv2.imread(img_path)
        img = PIL.Image.open(img_path)
        img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
        img = cv2.resize(img, (800, 1200))
        # cv2.imwrite(img_path, img, [cv2.IMWRITE_JPEG_QUALITY, 99, cv2.IMWRITE_JPEG_OPTIMIZE, 1])
        img = PIL.Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        img.save(img_path, quality=99, optimize=True)


if __name__ == "__main__":
    cut_cut(
            '1200(1).jpg',
            # '1200(2).jpg',
            # '1200(3).jpg',
            # '1200(4).jpg', 
            '1200(5).jpg',
            path=r'D:\code_python\office_automation\2-26spacious\U258\主图'
            )
